//
//  XMDiscoverSearchView.swift
//  XMWeimo
//
//  Created by ios001 on 16/7/23.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class XMDiscoverSearchView: UIView {

    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: 0, width: SCREENW, height: 35))
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 监听方法
    func buttonClick(){
        // 更新约束
        self.textFiled.snp_updateConstraints { (make) -> Void in
            make.trailing.equalTo(self)
        }
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            self.layoutIfNeeded()
            }) { (_) -> Void in
                // 取消第一响应者
                self.textFiled.resignFirstResponder()
        }
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        backgroundColor = RandomColor()
        // 添加控件
        addSubview(cancelButton)
        addSubview(textFiled)
        // 添加约束
        cancelButton.snp_makeConstraints { (make) -> Void in
            make.width.equalTo(50)
            make.top.bottom.trailing.equalTo(self)
        }
        textFiled.snp_makeConstraints { (make) -> Void in
            make.top.leading.bottom.equalTo(self)
            make.trailing.equalTo(self)
        }
    }
    
    // MARK: - 懒加载控件
    // 取消按钮
    private lazy var cancelButton: UIButton = {
       let button = UIButton()
        // 添加点击事件
        button.addTarget(self, action: "buttonClick", forControlEvents: UIControlEvents.TouchUpInside)
        button.setTitle("取消", forState: UIControlState.Normal)
        button.setTitleColor(ThemeColor, forState: UIControlState.Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        return button
    }()
    
    // 输入框
    private lazy var textFiled: UITextField = {
        let img = UIImageView(imgName: "searchbar_textfield_search_icon")
        img.contentMode = .Center
        img.frame.size = CGSize(width: 35, height: 35)
        let text = UITextField()
        text.layer.borderColor = ThemeColor.CGColor
        text.layer.borderWidth = 2
        text.placeholder = "请输入您要检索的信息"
        text.backgroundColor = UIColor.whiteColor()
        text.leftView = img
        text.leftViewMode = .Always
        text.delegate = self
        return text
    }()
}

extension XMDiscoverSearchView: UITextFieldDelegate {
    func textFieldDidBeginEditing(textField: UITextField) {
        self.textFiled.snp_updateConstraints { (make) -> Void in
            make.trailing.equalTo(self).offset(-50)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.layoutIfNeeded()
        }
    }
}
